/**
 * 
 */
package com.novartis.nims.imagedc.configuration;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

/**
 * @author snydejo2
 *
 */
public class ConfigurationHelper {
	
	private static Logger logger = Logger.getLogger(ConfigurationHelper.class);
	private static final String PROP_FILE = "application.properties";
	private static Properties applicationProperties = null;
	
	private static Properties applicationProperties() throws IOException {
		if (applicationProperties == null) {
			applicationProperties = new Properties();
			InputStream inStream = ConfigurationHelper.class.getResourceAsStream(PROP_FILE);
			applicationProperties.load(inStream);
		}
		
		return applicationProperties;
	}
	
	public static String getScanServiceUrl() throws Exception {
		String returnValue = applicationProperties().getProperty("ScanServiceUrl");
		
		if (returnValue == null) {
			//TODO: custom exception type
			throw new Exception("Couldn't find configuration property ScanServiceUrl");
		}
		
		logger.debug("ScanServiceUrl = " + returnValue);
		
		return returnValue;
	}
	
	public static Properties parseDicomConformanceSpec(InputStream conformanceSpec, InputStream transformation) throws Exception {
		Properties result = null;
		
		try {
			result = new Properties();

			StreamSource nimsRules = new StreamSource(conformanceSpec);
			StreamSource nimsToMircXsl = new StreamSource(transformation);

			TransformerFactory tf = TransformerFactory.newInstance();
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			StreamResult streamResult = new StreamResult(outStream);
			try {
				Transformer t = tf.newTransformer(nimsToMircXsl);
				t.transform(nimsRules, streamResult);
			} catch (TransformerException e) {
				//TODO: define configuration exception
				throw new Exception("Internal problem generating anonymization rules. " +
						"The application was probably configured and deployed incorrectly.", e);
			}

			try {
				result.load(new ByteArrayInputStream(outStream.toByteArray()));
			} catch (IOException e) {
				// reaching this means programmer error since ByteArrayInputStream
				// shouldn't cause an IOException on any operations
				throw new IllegalArgumentException(e);
			}
		} finally {
			try { conformanceSpec.close(); transformation.close(); } catch (IOException ignore) {}
		}
		
		return result;
	}

}
